﻿using System;
using System.Data;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using ConfigLibrary;
using MySql.Data;
using MySql.Data.MySqlClient;
using MailClient;
using System.Threading.Tasks;
using Contacts;
using System.Collections.Generic;

namespace MailClient.Queue
{
	/// <summary>
	/// Marshalls emails into and out of a database.  Sets our own Message Unique Id indenpdent of the mail server.
	/// 
	/// </summary>
	public class SwitchBoard
	{
		#region Private Declarations
		// Config info
		// Globals
		private MailMessage _msg;
		private System.Net.Mail.MailMessage _email;
		private int toggle;
		private MessageEventArgs Margs;
		#endregion

		#region Ctor
		public SwitchBoard(MailMessage msg)
		{
			_msg = msg;
			//loads the config file
			toggle = 1;
		}
		#endregion

		#region Private methods
		private DataRow[] Retrieve(string ContactName)
		{
			DataSet ContactsDatabase = Mail.Connections.connections.Contacts;
			DataTable ContactsTable = ContactsDatabase.Tables["contacts"];
			string query = "FullName LIKE '*" + ContactName + "*'";
			System.Data.DataRow[] rows = ContactsTable.Select(query);
			return rows;
		}

		#endregion
		public delegate void CommandCompleteHandler(MessageEventArgs e);
		public event CommandCompleteHandler CommandComplete;
		
		#region public methods
		public void Process()
		{
			/* Here is where we need to do several things.
			 * 1. idenify if the emial is an incoming or outgoing
			 *  if it is incoming, log the sender and check for sever commands.
			 *  send the email to the incoming handler.
			 *  2. if it is outgoing, check that the recipient matches the
			 *  original sender for the reply. log it.
			 */
			switch (toggle)
			{
				case 1:
					// incoming mail
					Retrieve(_msg.SenderDisplayName);
					Margs = new MessageEventArgs(_msg, "Incoming email processed");
					if (_email != null)
						break;
					break;
				case 2:
					Margs = new MessageEventArgs(_msg, "Incoming case 2 TODO");
					break;
			}
			if (CommandComplete != null)
				CommandComplete(Margs);
		}
		#endregion
		#region Public Properties
		public List<string>[] ContactResults { get; private set;}
		#endregion
	}
}
